﻿using csLTDMC;
using EasyFlow.Motion;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Kimd.DMC3800Card
{
    public class DMC3800CardCardOperator : ICard
    {
        public bool IsError{get;set;}

        public string LastError{get;set;}

        public bool CheckApiResult(short rtn, string err)
        {
            if (rtn != 0)
            {
                //_isApiErr = true;
                //string errorStr = ErrorCode2ErrorStr(rtn);
                //MachineMessage.CallException(ExceptionType.FatalErr, "轴卡", $"[{rtn}{errorStr}]:{err}", MachineErrCode.CardErr);
                return false;
            }
            return true;
        }

        public bool Close()
        {
            return CheckApiResult(LTDMC.dmc_board_close(), "关闭卡失败!");
        }

        public bool Init()
        {
            return true;
        }

        public bool Open(short cardNo, string configFilePath = "")
        {
            short rtn = 0;
            ushort[] Cardids = new ushort[8];
            try
            {
                short num = LTDMC.dmc_board_init();//获取卡数量
                if (num <= 0 || num > 8)
                {
                    return CheckApiResult(-1, "初始化卡出错!");
                }
                ushort _num = 0;
                uint[] cardtypes = new uint[8];
                rtn = LTDMC.dmc_get_CardInfList(ref _num, cardtypes, Cardids);
            }
            catch (Exception ex)
            {
                return CheckApiResult(-1, $"初始化卡出错!{ex.Message}");
            }
            if (!CheckApiResult(rtn, "获取卡信息失败!"))
                return false;
            if (!string.IsNullOrEmpty(configFilePath))
            {
                rtn = LTDMC.dmc_download_configfile((ushort)cardNo, configFilePath);
                if (!CheckApiResult(rtn, "加载卡配置文件失败!"))
                    return false;
            }
            return true;
        }

        public bool Reset()
        {
            short rtn = LTDMC.dmc_board_reset();
            rtn += LTDMC.dmc_board_close();
            if (!CheckApiResult(rtn, "复位卡失败!"))
                return false;

            for (int i = 0; i < 15; i++)//总线卡硬件复位耗时15s左右
            {
                Thread.Sleep(1000);
            }

            LTDMC.dmc_board_init();
            if (!CheckApiResult(rtn, "复位后初始化卡失败!"))
                return false;
            return true;
        }
    }
}
